package com.xyw.code.authorization.server.oauth2.token;

import com.xyw.code.authorization.common.entity.vo.SecurityUser;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;

import java.util.HashMap;

/**
 * Created with IntelliJ IDEA.
 * User: xuyiwei
 * Date: 2020/4/27
 * Time: 下午6:20
 * Email: 1328312923@qq.com
 * 对JwtAccessTokenConverter 的 enhance进行重写，加入自定义的信息
 **/
public class CustomJwtAccessTokenConverter  extends JwtAccessTokenConverter {

    //这个是token增强器，想让jwt token携带额外的信息在这里处理
    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
        if (accessToken instanceof DefaultOAuth2AccessToken) {
            Object principal = authentication.getPrincipal();

            //这个principal是当时登录后存到securiy的东东，一般是用户实体，自己debug一下就知道了
            if (principal instanceof SecurityUser) {
                SecurityUser user = (SecurityUser) principal;
                HashMap<String, Object> map = new HashMap<>();

                //jwt默认已经自带用户名，无需再次加入
                map.put("userId", user.getUserId());
                map.put("deptId", user.getDeptId());
                ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(map);
            }
        }
        return super.enhance(accessToken, authentication);
    }

}
